package com.z.kq.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.z.common.context.UserContext;
import com.z.common.exception.BusinessException;
import com.z.common.web.vo.request.PageVo;
import com.z.kq.vo.UserScheVo;
import com.z.kq.entity.Sche;
import com.z.kq.mapper.ScheMapper;
import com.z.kq.service.IScheService;
import com.z.kq.utils.DateUtils;
import com.z.sys.entity.Dept;
import com.z.sys.entity.Festival;
import com.z.sys.entity.User;
import com.z.sys.service.IDeptService;
import com.z.sys.service.IFestivalService;
import com.z.sys.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * 排班管理Service业务层处理
 *
 * @author z
 * @date 2023-03-28
 */
@Service
public class ScheServiceImpl extends ServiceImpl<ScheMapper,Sche> implements IScheService {


    @Resource
    private IFestivalService festivalService;
    @Resource
    private IUserService userService;

    @Resource
    private IDeptService deptService;
    /**
     * 查询排班管理
     * @param sche 排班管理
     * @param pageVo
     * @return 排班管理 分页集合
     * */
    @Override
    public PageInfo<Sche> selectSchePage(Sche sche, PageVo pageVo) {
        PageHelper.startPage(pageVo.getPage(), pageVo.getLimit());
        List<Sche> data = selectScheList(sche);
        return new PageInfo<>(data);
    }
    @Override
    public List<Sche> selectScheList(Sche sche) {
        if("1".equals(sche.getDeptId())){
            sche.setDeptId("");
        }
        if(StringUtils.isEmpty(sche.getDeptId())){
            int powerLevel = UserContext.getPowerLevel("考勤");
            if(powerLevel != 0){
                List<Dept> deptList = deptService.getDeptListByRole();
                String full_path_sql = "(";
                if(deptList != null && deptList.size() > 0){
                    for(Dept dept : deptList){
                        full_path_sql += ("d.full_path like '" + dept.getFullPath() + "/%' or d.full_path = '" + dept.getFullPath() + "' or ");
                    };
                }
                full_path_sql += " user_id = "+UserContext.currentUser().getId()+")";
                Map<String, Object> map = new HashMap<>();
                map.put("full_path_sql", full_path_sql);
                sche.setParams(map);
            }
        }
        return baseMapper.selectScheList(sche);
    }

    @Override
    public List<UserScheVo> selectUserScheList(User user, Sche sche) {
        if("1".equals(user.getDeptId())){
            user.setDeptId(null);
        }
        if(StringUtils.isEmpty(sche.getDay())){
            sche.setDay(DateUtils.convertDate2String("yyyy-MM", new Date()));
        }
        List<User> userList = userService.selectUserList(user, "考勤");

        List<UserScheVo> list = new ArrayList<>();
        for(User u : userList){
            sche.setUserId(u.getId()+"");
            List<Sche> scheList = selectScheList(sche);
            Map<String, Sche> map = new HashMap<>();
            UserScheVo userScheVo = new UserScheVo();
            userScheVo.setUsername(u.getUsername());
            userScheVo.setUserSn(u.getUserSn());
            userScheVo.setScheType(u.getUsername());
            userScheVo.setScheName(u.getUsername());
            String scheType = "";
            String scheName = "";
            for(Sche s : scheList){
                String day = s.getDay().substring(8,10);
                setDayState(userScheVo, day, s.getScheName());
            }
            list.add(userScheVo);
        }
        return list;
    }

    private void setDayState(UserScheVo userScheVo, String day, String state) {
        switch (day){
            case "01":
                userScheVo.setD1(state);
                break;
            case "02":
                userScheVo.setD2(state);
                break;
            case "03":
                userScheVo.setD3(state);
                break;
            case "04":
                userScheVo.setD4(state);
                break;
            case "05":
                userScheVo.setD5(state);
                break;
            case "06":
                userScheVo.setD6(state);
                break;
            case "07":
                userScheVo.setD7(state);
                break;
            case "08":
                userScheVo.setD8(state);
                break;
            case "09":
                userScheVo.setD9(state);
                break;
            case "10":
                userScheVo.setD10(state);
                break;
            case "11":
                userScheVo.setD11(state);
                break;
            case "12":
                userScheVo.setD12(state);
                break;
            case "13":
                userScheVo.setD13(state);
                break;
            case "14":
                userScheVo.setD14(state);
                break;
            case "15":
                userScheVo.setD15(state);
                break;
            case "16":
                userScheVo.setD16(state);
                break;
            case "17":
                userScheVo.setD17(state);
                break;
            case "18":
                userScheVo.setD18(state);
                break;
            case "19":
                userScheVo.setD19(state);
                break;
            case "20":
                userScheVo.setD20(state);
                break;
            case "21":
                userScheVo.setD21(state);
                break;
            case "22":
                userScheVo.setD22(state);
                break;
            case "23":
                userScheVo.setD23(state);
                break;
            case "24":
                userScheVo.setD24(state);
                break;
            case "25":
                userScheVo.setD25(state);
                break;
            case "26":
                userScheVo.setD26(state);
                break;
            case "27":
                userScheVo.setD27(state);
                break;
            case "28":
                userScheVo.setD28(state);
                break;
            case "29":
                userScheVo.setD29(state);
                break;
            case "30":
                userScheVo.setD30(state);
                break;
            case "31":
                userScheVo.setD31(state);
                break;
        }
    }

    @Override
    public PageInfo<UserScheVo> selectUserSchePage(User user, Sche sche, PageVo pageVo) {
        PageHelper.startPage(pageVo.getPage(), pageVo.getLimit());
        List<UserScheVo> data = selectUserScheList(user, sche);
        return new PageInfo<>(data);
    }

    @Override
    public boolean save(Sche sche) {

        String[] ids = sche.getUserId().split(",");
        Date start = null;
        String endDateStr = sche.getDay().substring(0,5)+"12-31";
        List<Sche> list = new ArrayList<>();
        List<String> dateList = new ArrayList<>();

        if(sche.getSort().equals("0")){
            Festival festival = festivalService.getWorksAndRests(sche.getDay().substring(0,4));
            try {
                start = DateUtils.convertString2Date(sche.getDay());
                int max = 366;
                int i = 0;
                String tempDateStr = "";
                while (!endDateStr.equals(tempDateStr) && i<=max){
                    Date tempDate = DateUtils.plusDateC(start, i);
                    tempDateStr = DateUtils.convertDate2String(tempDate);
                    dateList.add(tempDateStr);
                    boolean rest_flag = false;
                    rest_flag = DateUtils.isWeekOfDate(tempDate); //是否周末
                    if(rest_flag){// 是否补班
                        if(festival.getWorkDate().contains(tempDateStr)){
                            rest_flag = false;
                        }
                    }else { // 是否节假日
                        if(festival.getRestDate().contains(tempDateStr)){
                            rest_flag = true;
                        }
                    }
                    for(String id : ids){
                        Sche temp = new Sche();
                        BeanUtils.copyProperties(sche, temp, "userId");
                        temp.setUserId(id);
                        temp.setDay(tempDateStr);
                        if(rest_flag){
                            temp.setScheStage("休");
                        }
                        list.add(temp);
                    }
                    i++;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else {
            try {
                start = DateUtils.convertString2Date(sche.getDay());
                char[] law = sche.getRemark().toCharArray();
                String[] stages = sche.getSortOldStage().split("；");
                Map<String, String> stageMap = new HashMap<>();
                for(String s : stages) {
                    String temp[] = s.split("代表：");
                    stageMap.put(temp[0], temp[1]);
                }
                int max = 366;
                int i = 0;
                int lawIndex = 0;
                int len = law.length - 1;
                String tempDateStr = "";
                while (!endDateStr.equals(tempDateStr) && i<=max){
                    Date tempDate = DateUtils.plusDateC(start, i);
                    tempDateStr = DateUtils.convertDate2String(tempDate);
                    String stage = stageMap.get("" + law[lawIndex]);
                    dateList.add(tempDateStr);
                    for(String id : ids){
                        Sche temp = new Sche();
                        BeanUtils.copyProperties(sche, temp, new String[]{"userId","sort","sortOldStage"});
                        temp.setUserId(id);
                        temp.setDay(tempDateStr);
                        temp.setScheStage(stage);
                        list.add(temp);
                    }
                    i++;
                    if(lawIndex<len){
                        lawIndex ++ ;
                    }else {
                        lawIndex = 0;
                    }
                }
            } catch (Exception e) {
                throw new BusinessException(e.getMessage());
            }
        }

        baseMapper.delete(new QueryWrapper<Sche>().in("user_id", ids).in("day", dateList));
        return saveBatch(list, 5000);
    }
}
